import {createSlice, PayloadAction} from "@reduxjs/toolkit";
import {findLabelByPath, getMenus} from "@/utils/MuenUtils.tsx";

/**
 * @author 橘柚
 * @Date 2023/11/12 20:32
 * @Description 面包屑导航的路径
 */
export interface IBreadcrumb {
  pathArray: Array<{ name: string; path: string }>
}

const breadcrumbSlice = createSlice({
  name: 'breadcrumb',
  initialState: {
    pathArray: [{name: '首页', path: '/home'}]
  },
  reducers: {
    addPath: (state, action: PayloadAction<string>) => {
      const currentPath = action.payload === '/' ? '/home' : action.payload
      if (currentPath === '/home') {
        state.pathArray = [{name: '首页', path: '/home'}]
        return
      }
      // 查找给定的 path 在数组中的索引
      const index = state.pathArray.findIndex(item => item.path === currentPath);
      if (index !== -1) {
        // 如果给定的 path 存在于原数组中
        state.pathArray = [...state.pathArray.slice(0, index + 1),];
      } else {
        // 如果给定的 path 不存在于原数组中
        const menus = getMenus()
        const randomName = findLabelByPath(menus, currentPath); // 随机给定一个名字
        state.pathArray = [...state.pathArray, {name: randomName, path: currentPath}]; // 将新对象放在数组最后
      }
    }
  }
})

export const {addPath} = breadcrumbSlice.actions

export const breadcrumbReducers = breadcrumbSlice.reducer